from sqlalchemy import and_, select
from sqlalchemy.ext.asyncio import AsyncSession

from src.application.server.enums import ServerPrivacy, ServerStatus, ServerType
from src.infrastructure.db.models import ProxyProvider, Server


async def query_providers(
    session: AsyncSession,
    proxy_type: ServerType,
    proxy_privacy: ServerPrivacy,
    country_id: int,
) -> list[ProxyProvider]:
    q = (
        select(ProxyProvider)
        .join(ProxyProvider.servers)
        .filter(
            and_(
                Server.status == ServerStatus.active,
                Server.proxy_type == proxy_type,
                Server.proxy_privacy == proxy_privacy,
                Server.country_id == country_id,
            )
        )
    )

    res = await session.execute(q)

    return res.scalars().unique().all()


async def get_provider(session: AsyncSession, provider_id: int) -> ProxyProvider:
    q = select(ProxyProvider).where(ProxyProvider.id == provider_id)
    res = await session.execute(q)

    return res.scalar()
